Some examples of using Laravel Collections methods instead of Twig filters in Craft CMS 4.
The improvements with eager-loading elements are the primary advantage of collections. But we can use the collect()
method anywhere to convert data to a collection and then manipulate it with the Laravel Collections methods.
We’ll take this standard element query, and, instead of calling the .all()
method to execute the query and return results, we’ll call .collect()
, which will also execute a query but return the results as a Laravel Collections array.
{% set entries = craft.entries()
.section('blog')
.limit(25)
.collect()
%}
This opens up to us all of the methods available to a Collections array. The best place to refer to for these methods is the Laravel documentation.
Let’s group entries based on the section handle. Typically, I’d use the group
filter filter in Twig:
{% set entries = craft.entries()
.section(['blog', 'podcast', 'review'])
.limit(25)
.all() %}
{% set groupBySection = entries | group('section.handle') %}
But since we already have a collection, we can use the collection groupBy()
method:
{% set entries = craft.entries()
.section(['blog', 'podcast', 'review'])
.limit(25)
.collect() %}
{% set groupBySection = entries.groupBy('section.handle') %}
Similarly, we can replace the batch
filter with the chunk()
method. Here’s the batch
filter:
{% set entries = craft.entries()
.section(['blog', 'podcast', 'review'])
.limit(25)
.all() %}
{% set setOfThree = entries | batch(3) %}
And the same results but using a collection and the chunk()
method:
{% set entries = craft.entries()
.section(['blog', 'podcast', 'review'])
.limit(25)
.collect() %}
{% set setOfThree = entries.chunk(3) %}
And, these are just two examples of using collections methods in Twig. There are dozens of methods to choose from!